package com.ws.webpacket.push;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.ws.webpacket.BuildConfig;
import com.ws.webpacket.activity.MainActivity;
import com.ws.webpacket.util.HLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;


/**
 * 自定义接收器
 * JPushInterface.ACTION_REGISTRATION_ID   注册得到ID
 * JPushInterface.ACTION_MESSAGE_RECEIVED  收到了自定义消息 Push
 * JPushInterface.ACTION_NOTIFICATION_RECEIVED  收到了通知 Push
 * JPushInterface.ACTION_NOTIFICATION_OPENED    用户点击了通知
 * JPushInterface.ACTION_NOTIFICATION_CLICK_ACTION  用户点击了通知栏中自定义的按钮
 * JPushInterface.ACTION_CONNECTION_CHANGE    JPush 服务的连接状态发生变化
 * JPushInterface.ACTION_RICHPUSH_CALLBACK
 */
public class HReceiveAction extends BroadcastReceiver {
    private static final String TAG = "JIGUANG-Example";
    private Vibrator mVibrator;
    private Ringtone mRingtone;

    @Override
    public void onReceive (Context context, Intent intent) {

        Bundle bundle = intent.getExtras();
//        HLog.I("HReceiveAction  action="+intent.getAction()+" \n  "+ printBundle(bundle));
        // 接收到 ID
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);

//            HLog.I("注册成功  ID： " + regId);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            rining(context);
//            HLog.I("[MyReceiver] 接收到推送下来的通知 " + notificationId);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
//            HLog.I("[MyReceiver] 用户点击打开了通知");
            showInActivity(context, bundle);
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            //  Push  自定义消息   获取消息内容  bundle.getString(JPushInterface.EXTRA_MESSAGE)
        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            if (!connected && BuildConfig.DEBUG)
                Toast.makeText(context, "JPush disconnect", Toast.LENGTH_SHORT).show();
        }
    }

    private void rining (Context context) {
        if (mVibrator == null) {
            mVibrator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
        }
        mVibrator.cancel();
        if (mVibrator.hasVibrator()) {
            long pet[] ={0,200,100,200,100,500};
            mVibrator.vibrate(pet,-1);
        }

        if (mRingtone == null) {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            mRingtone = RingtoneManager.getRingtone(context, notification);
        }
        mRingtone.play();

    }

    private void showInActivity (Context context, Bundle bundle) {
        String url = null;
        try {
            JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
            url = json.optString("url");
        } catch (JSONException e) {
            e.printStackTrace();
        }


        if (MainActivity.avtivityCreated) {
            if (url != null && !url.isEmpty()) {
                MainActivity.actionWebOption.loadUrl(url);
            }
        } else {
            MainActivity.adUrl = url;
        }

        Intent i = new Intent(context, MainActivity.class);
        i.putExtras(bundle);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(i);
    }

    // 打印所有的 intent extra 数据
    private static String printBundle (Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    HLog.I("This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    HLog.I("Get message extra JSON error!");
                }
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.get(key));
            }
        }
        return sb.toString();
    }


}
